import * as T from '../actionTypes/basic'
import { setUncompleteMessage, setUncompleteMessageNum } from '../actions/basic'
import axios from 'axios'
import { message } from 'antd'
import { Dispatch } from 'redux'
import { UserInfo } from '@src/components/schema/basic';
import { MessageSchema } from '@src/components/schema/message'

export interface INIT_BASIC_STATE {
  userInfo: UserInfo,
  token: string,
  sendTime: number | undefined,
  mobile: string,
  uncompleteMessageList: MessageSchema[],
  uncompleteNum: number
}

const initialState: INIT_BASIC_STATE = {
  userInfo: {} as UserInfo,
  token: '',
  sendTime: undefined,
  mobile: '',
  uncompleteMessageList: [],
  uncompleteNum: 0
}

// 设置基本信息
function reducer (state = initialState, action: { type: string, data: any, dispatch: Dispatch }) {
  switch (action.type) {
    case T.SET_USERINFO:
      return {
        ...state,
        userInfo: action.data
      }
    case T.SET_TOKEN:
      return {
        ...state,
        token: action.data
      }
    case T.SET_SEND_TIME:
      return {
        ...state,
        sendTime: action.data
      }
    case T.SET_LOGIN_MOBILE:
      return {
        ...state,
        mobile: action.data
      }
    case T.UPDATE_UNCOMPLETE_MESSAGE:
      getUncompleteMessage(state, action.dispatch)
      return state
    case T.SET_UNCOMPLETE_MESSAGE:
      return {
        ...state,
        uncompleteMessageList: action.data
      }
    case T.SET_UNCOMPLETE_MESSAGE_NUM:
      return {
        ...state,
        uncompleteNum: action.data
      }
    default:
      return state
  }
}

export default reducer

// 更新未读消息列表
function getUncompleteMessage (state: INIT_BASIC_STATE, dispatch: Dispatch) {
  if (!state.token) {
    return null
  }
  axios.get('/api/xapc/message', {
    params: {
      page: 1,
      limit: 10,
      condition: JSON.stringify([
        { k: 'complete_datetime', o: 'null' }
      ]),
      uid: state.userInfo.id
    },
    headers: {
      'Content-Type': 'application/json',
      Authorization: `Bearer ${state.token}`
    },
    timeout: 1000 * 30
  }).then(res => {
    const data = res.data.data
    if (res.data.status === 1 && state.token) {
      dispatch(setUncompleteMessage(data.list))
      dispatch(setUncompleteMessageNum(data.total))
    } else {
      message.warning(data.message)
    }
  })
}
